﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.Bill.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using LBKDHelper.PluginHelpers;
using LM.YF.K3Cloud.Plugin.Models;
using System;
using System.ComponentModel;

namespace LM.YF.K3Cloud.Plugin
{
    /// <summary>
    /// 鹿奔 240413
    /// </summary>
    [Description("发货通知单表单插件"), HotUpdate]
    public class NoticeOrderBillPlugin : AbstractBillPlugIn
    {
        #region MyRegion

        /// <summary>
        /// 运输路线
        /// </summary>
        readonly ElementKeySchema F_RDLV_route = new ElementKeySchema
        {
            FormKey = "F_RDLV_route",
            DbKey = "F_RDLV_ROUTE",
            OrmKey = "F_RDLV_route"
        };

        /// <summary>
        /// 发货组织
        /// </summary>
        readonly ElementKeySchema FDeliveryOrgID = new ElementKeySchema
        {
            FormKey = "FDeliveryOrgID",
            DbKey = "FDELIVERYORGID",
            OrmKey = "DeliveryOrgID"
        };

        /// <summary>
        /// 客户
        /// </summary>
        readonly ElementKeySchema FCustomerID = new ElementKeySchema
        {
            FormKey = "FCustomerID",
            DbKey = "FCUSTOMERID",
            OrmKey = "CustomerID"
        };

        /// <summary>
        /// 承运商
        /// </summary>
        readonly ElementKeySchema FCarrierID = new ElementKeySchema
        {
            FormKey = "FCarrierID",
            DbKey = "FCARRIERID",
            OrmKey = "CarrierID"
        };

        /// <summary>
        /// 销售部门
        /// </summary>
        readonly ElementKeySchema FSaleDeptID = new ElementKeySchema
        {
            FormKey = "FSaleDeptID",
            DbKey = "FSALEDEPTID",
            OrmKey = "SaleDeptID"
        };

        /// <summary>
        /// 成本中心
        /// </summary>
        readonly ElementKeySchema F_RDLV_CostCenter = new ElementKeySchema
        {
            FormKey = "F_RDLV_CostCenter",
            DbKey = "F_RDLV_COSTCENTER",
            OrmKey = "F_RDLV_CostCenter"
        };

        /// <summary>
        /// 销售主体
        /// </summary>
        readonly ElementKeySchema F_RDLV_saler2 = new ElementKeySchema
        {
            FormKey = "F_RDLV_saler2",
            DbKey = "F_RDLV_SALER2",
            OrmKey = "F_RDLV_saler2"
        };

        #endregion

        public override void DataChanged(DataChangedEventArgs e)
        {
            base.DataChanged(e);

            if (e.Field.Key.Equals(FDeliveryOrgID.FormKey) || e.Field.Key.Equals(FCustomerID.FormKey) || e.Field.Key.Equals(F_RDLV_saler2.FormKey))
            {
                //获取起运点
                var stockOrgId = Convert.ToInt32((View.Model.GetValue(FDeliveryOrgID.FormKey) as DynamicObject)?["Id"]);
                string strSql = $"select distinct FID  from RDLV_t_startpoint_entry where F_RDLV_ORG = {stockOrgId}";
                var fStartCodeDynamic = DBUtils.ExecuteDynamicObject(this.Context, strSql);
                if (fStartCodeDynamic != null && fStartCodeDynamic.Count > 0)
                {
                    string fstartCode = fStartCodeDynamic[0]["fid"].ToString() ?? "0";
                    this.Model.SetValue("F_QLTK_StartCode", fstartCode);
                }
                GetRoute();
            }
            else if (e.Field.Key.Equals(FSaleDeptID.FormKey))
            {
                GetCostCenter();
            }
        }

        public override void BeforeSave(BeforeSaveEventArgs e)
        {
            base.BeforeSave(e);
            GetCostCenter();
        }

        /// <summary>
        /// 获取运输路线
        /// </summary>
        private void GetRoute()
        {
            var regionId = Convert.ToInt32((View.Model.GetValue(FCustomerID.FormKey) as DynamicObject)?["F_RDLV_Region_Id"]);
            var stockOrgId = Convert.ToInt32((View.Model.GetValue(FDeliveryOrgID.FormKey) as DynamicObject)?["Id"]);
            var saleBodyId = Convert.ToInt32((View.Model.GetValue(F_RDLV_saler2.FormKey) as DynamicObject)?["Id"]);
            var routeData = SalesOrderBillPlugin.GetRoute(Context, regionId, stockOrgId, saleBodyId);
            if (routeData.Failure == null)
            {
                View.Model.SetValue(F_RDLV_route.FormKey, routeData.RouteId);
                View.Model.SetValue(FCarrierID.FormKey, routeData.CarrierId);
            }
            else
            {
                View.Model.SetValue(F_RDLV_route.FormKey, "");
                View.Model.SetValue(FCarrierID.FormKey, "");
            }
            View.UpdateView(F_RDLV_route.FormKey);
        }

        /// <summary>
        /// 获取发货组织对应的成本中心
        /// </summary>
        private void GetCostCenter()
        {
            var deliveryOrg = View.Model.GetValue(FDeliveryOrgID.FormKey) as DynamicObject;
            var deliveryOrgName = PluginUtils.GetLocaleValue(deliveryOrg);
            var deliveryOrgId = Convert.ToInt32(deliveryOrg?["Id"]);
            int costCenterId;
            if ("内蒙古新威远生物化工有限公司".Equals(deliveryOrgName))
            {
                // 内蒙古的部门，固定用其组织下的 物流管理部
                costCenterId = DBUtils.ExecuteScalar(Context, $@"select a.FDEPTID
                    from T_BD_DEPARTMENT as a
                    inner join T_BD_DEPARTMENT_L as b on b.FLOCALEID = 2052 and b.FDEPTID = a.FDEPTID
                    where a.FUSEORGID = {deliveryOrgId}
                    and b.FNAME = '物流管理部'", 0);
            }
            else
            {
                var deptNumber = Convert.ToString((View.Model.GetValue(FSaleDeptID.FormKey) as DynamicObject)?["Number"]);
                costCenterId = DBUtils.ExecuteScalar(Context, $@"select FDEPTID
                    from T_BD_DEPARTMENT
                    where FNUMBER = '{deptNumber}' and FUSEORGID = '{deliveryOrgId}';", 0);
            }
            View.Model.SetValue(F_RDLV_CostCenter.FormKey, costCenterId);
        }
    }
}
